﻿package com.cw.war.ui
{
	import flash.display.InteractiveObject;
	import flash.events.MouseEvent;
	import flash.utils.Dictionary;
	import flash.utils.Timer;

	/**
	 * 单击处理器
	 * @author DanielLu
	 */
	public class ClickManager
	{
		private static var clickMap : Dictionary = new Dictionary ();

		/**
		 * 就是为了获取在按下鼠标200毫秒内抬起按键的事件
		 * 双击的判断
		 * 是在200毫秒内，单击了两次
		 * 他并没有记录单击次数
		 * 添加单击事件侦听
		 * @param obj				要添加侦听器的交互对象
		 * @param listener			要添加的侦听器
		 * @param useCapture		
		 * @param priority			优先级
		 * @param useWeakReference	使用弱引用
		 */
		public static function addClickListener ( obj : InteractiveObject , listener : Function , useCapture : Boolean = false , priority : int = 0 , useWeakReference : Boolean = false ) : void
		{
			if (clickMap[obj] == null)
			{
				var listenerObj : Object = new Object ();
				var timer : Timer = new Timer ( 200 , 1 );
				// 设置单击侦听
				listenerObj.onMouseDown = function ( e : MouseEvent ) : void
				{
					timer.stop ();
					timer.reset ();
					timer.start ();
				};
				listenerObj.onMouseClick = function ( e : MouseEvent ) : void
				{
					if (timer.running)
					{
						obj.dispatchEvent ( new MouseEvent ( "_____onClick" , e.bubbles , e.cancelable , e.localX , e.localY , e.relatedObject , e.ctrlKey , e.altKey , e.shiftKey , e.buttonDown , e.delta ) );
					}
					timer.stop ();
					timer.reset ();
				};
				// 添加侦听器
				obj.addEventListener ( MouseEvent.MOUSE_DOWN , listenerObj.onMouseDown , useCapture , 10000000 , useWeakReference );
				obj.addEventListener ( MouseEvent.MOUSE_UP , listenerObj.onMouseClick , useCapture , 0 , useWeakReference );
				clickMap[obj] = listenerObj;
			}
			// 添加侦听器
			obj.addEventListener ( "_____onClick" , listener , useCapture , priority , useWeakReference );
		}

		/**
		 * 删除单击侦听器
		 */
		public static function removeClickListener ( obj : InteractiveObject , listener : Function , useCapture : Boolean = false ) : void
		{
			if (clickMap[obj] != null)
			{
				obj.removeEventListener ( "_____onClick" , listener , useCapture );
				if (! obj.hasEventListener ( "_____onClick" ))
				{
					obj.removeEventListener ( MouseEvent.MOUSE_DOWN , clickMap[obj].onMouseDown , useCapture );
					obj.removeEventListener ( MouseEvent.CLICK , clickMap[obj].onMouseClick , useCapture );
					delete clickMap[obj];
				}
			}
		}
	}
}
